//
//  CCNavigationController.m
//  MXApp
//
//  Created by CC on 2019/6/1.
//  Copyright © 2019 Shanghai YingXiang Network Technology Co., Ltd. All rights reserved.
//

#import "CCNavigationController.h"
#import "BaseViewController.h"
#import "LcNavigationBar.h"
#import "LcFoundation.h"

@interface CCNavigationController () <UINavigationControllerDelegate>

@end

@implementation CCNavigationController

- (instancetype)init {
  self = [super initWithNavigationBarClass:LcNavigationBar.class toolbarClass:nil];
  return self;
}

- (instancetype)initWithRootViewController:(UIViewController*)rootViewController {
  LC_CHECK_NOT_NULL(rootViewController);
  self = [super initWithNavigationBarClass:LcNavigationBar.class toolbarClass:nil];
  if (self) {
    [self setViewControllers:@[ rootViewController ]];
  }
  return self;
}

- (void)viewDidLoad {
  [super viewDidLoad];
}

- (void)pushViewController:(UIViewController*)viewController
                  animated:(BOOL)animated {
  [self setFromViewController:viewController];
  [super pushViewController:viewController animated:animated];
}

- (void)setFromViewController:(UIViewController *)toViewController {
  UIViewController* topViewController = self.topViewController;
  if ([topViewController isKindOfClass:[BaseViewController class]]) {
    [(BaseViewController *)toViewController setFromViewController:(BaseViewController *)topViewController];
  }
}

- (UIViewController*)popViewControllerAnimated:(BOOL)animated {
  if (self.viewControllers.count == 2) {
    NSArray* popedControllers = [super popToRootViewControllerAnimated:animated];
    return popedControllers.firstObject;
  } else {
    return [super popViewControllerAnimated:animated];
  }
}

- (UIViewController*)childViewControllerForStatusBarStyle {
  return self.topViewController;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
  // fix TabBar pop under presentViewController
  float systemVersion = [UIDevice currentDevice].systemVersion.floatValue;
  if (systemVersion < 9.0) {
    UITabBarController* tabBarController = viewController.tabBarController;
    if (tabBarController != nil) {
      if (tabBarController.tabBar.hidden != viewController.hidesBottomBarWhenPushed) {
        tabBarController.tabBar.hidden = viewController.hidesBottomBarWhenPushed;
      }
    }
  }
}

@end

